package com.bk.bookviews.common;

import com.bk.bookviews.exception.BusinessException;
import com.bk.bookviews.exception.BusinessExceptionEnum;
import com.bk.bookviews.util.RedisUtil;
import com.bk.bookviews.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = TokenUtil.getRequestToken(request);
//        如果token为空
        if (StringUtils.isBlank(token)) {
            throw new BusinessException(BusinessExceptionEnum.TOKEN_IS_NULL);
        }
//        1. 根据token，查询用户信息
        Object o = redisUtil.get(token);
        if (o == null){
            throw new BusinessException(BusinessExceptionEnum.LOGON_FAILURE);
        }
        return true;
    }
}
